/*
package green

import (

	"encoding/json"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	green20220302 "github.com/alibabacloud-go/green-20220302/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/gin-gonic/gin"
	"net/http"

)

type GreenController struct{}

	func (g *GreenController) Green(c *gin.Context) {
		// 获取待审核内容
		textToCheck := c.Query("text")
		if textToCheck == "" {
			c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "missing 'text' parameter"})
			return
		}

		// 构建请求参数
		serviceParams, err := json.Marshal(map[string]interface{}{
			"content": textToCheck,
		})
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "failed to marshal service parameters"})
			return
		}

		// 配置阿里云客户端（推荐从环境变量读取 AK/SK）
		config := createGreenClientConfig()
		client, err := green20220302.NewClient(config)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "failed to create green client", "details": err.Error()})
			return
		}

		// 构造请求体
		request := &green20220302.TextModerationPlusRequest{
			Service:           tea.String("query_security_check"),
			ServiceParameters: tea.String(string(serviceParams)),
		}

		// 设置运行时选项
		runtime := &util.RuntimeOptions{
			ReadTimeout:    tea.Int(10000),
			ConnectTimeout: tea.Int(10000),
		}

		// 发起调用
		result, err := client.TextModerationPlusWithOptions(request, runtime)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": "green moderation failed", "details": err.Error()})
			return
		}

		// 处理 HTTP 响应状态码
		if *result.StatusCode != http.StatusOK {
			c.AbortWithStatusJSON(int(*result.StatusCode), gin.H{
				"error":  "non-OK HTTP status",
				"status": *result.StatusCode,
			})
			return
		}

		body := result.Body

		// 处理业务响应码
		if *body.Code != http.StatusOK {
			c.AbortWithStatusJSON(http.StatusOK, gin.H{
				"success": false,
				"code":    *body.Code,
				"message": *body.Message,
			})
			return
		}

		// 成功返回结果
		c.JSON(http.StatusOK, gin.H{
			"success": true,
			"data":    *body.Data,
		})
	}

// createGreenClientConfig 创建并配置阿里云 Green 客户端配置

	func createGreenClientConfig() *openapi.Config {
		return &openapi.Config{
			AccessKeyId:     tea.String("LTAI5t6AsUdBoEXLycEhes9L"),       // 替换为实际获取方式
			AccessKeySecret: tea.String("35eK6gzOsBXFS96nDny8ae7SsdWPLw"), // 替换为实际获取方式
			RegionId:        tea.String("cn-shanghai"),
			Endpoint:        tea.String("green-cip.cn-shanghai.aliyuncs.com"),
			ConnectTimeout:  tea.Int(3000),
			ReadTimeout:     tea.Int(6000),
		}
	}
*/
package green

import (
	"encoding/json"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	green20220302 "github.com/alibabacloud-go/green-20220302/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/gin-gonic/gin"
	"net/http"
)

type GreenController struct{}

type GreenRequest struct {
	Title       string `json:"title"`
	Description string `json:"description"`
}

type ViolationDetail struct {
	Label       string `json:"label"`
	Description string `json:"description"`
	Confidence  int    `json:"confidence"`
}

type GreenResponse struct {
	Success      bool              `json:"success"`
	IsPassed     bool              `json:"isPassed"`
	RiskLevel    string            `json:"riskLevel"`
	Violations   []ViolationDetail `json:"violations,omitempty"`
	ErrorMessage string            `json:"errorMessage,omitempty"`
}

func (g *GreenController) Green(c *gin.Context) {
	// 获取请求参数
	var req GreenRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, GreenResponse{
			Success:      false,
			ErrorMessage: "Invalid request body",
		})
		return
	}

	// 检查必填字段
	if req.Title == "" && req.Description == "" {
		c.JSON(http.StatusBadRequest, GreenResponse{
			Success:      false,
			ErrorMessage: "Title or description is required",
		})
		return
	}

	// 合并文本内容进行审核
	textToCheck := req.Title + "\n" + req.Description

	// 构建请求参数
	serviceParams, err := json.Marshal(map[string]interface{}{
		"content": textToCheck,
	})
	if err != nil {
		c.JSON(http.StatusInternalServerError, GreenResponse{
			Success:      false,
			ErrorMessage: "Failed to marshal service parameters",
		})
		return
	}

	// 配置阿里云客户端
	config := createGreenClientConfig()
	client, err := green20220302.NewClient(config)
	if err != nil {
		c.JSON(http.StatusInternalServerError, GreenResponse{
			Success:      false,
			ErrorMessage: "Failed to create green client",
		})
		return
	}

	// 构造请求体
	request := &green20220302.TextModerationPlusRequest{
		Service:           tea.String("query_security_check"),
		ServiceParameters: tea.String(string(serviceParams)),
	}

	// 设置运行时选项
	runtime := &util.RuntimeOptions{
		ReadTimeout:    tea.Int(10000),
		ConnectTimeout: tea.Int(10000),
	}

	// 发起调用
	result, err := client.TextModerationPlusWithOptions(request, runtime)
	if err != nil {
		c.JSON(http.StatusInternalServerError, GreenResponse{
			Success:      false,
			ErrorMessage: "Green moderation service error",
		})
		return
	}

	// 处理HTTP响应状态码
	if *result.StatusCode != http.StatusOK {
		c.JSON(int(*result.StatusCode), GreenResponse{
			Success:      false,
			ErrorMessage: "Non-OK HTTP status from green service",
		})
		return
	}

	body := result.Body

	// 处理业务响应码
	if *body.Code != http.StatusOK {
		c.JSON(http.StatusOK, GreenResponse{
			Success:      false,
			ErrorMessage: *body.Message,
		})
		return
	}

	// 解析审核结果
	riskLevel := *body.Data.RiskLevel
	isPassed := riskLevel != "high"

	// 提取违规详情
	var violations []ViolationDetail
	if !isPassed && body.Data.Result != nil {
		for _, r := range body.Data.Result {
			violations = append(violations, ViolationDetail{
				Label:       *r.Label,
				Description: *r.Description,
				Confidence:  int(*r.Confidence),
			})
		}
	}

	// 返回统一格式的响应
	c.JSON(http.StatusOK, GreenResponse{
		Success:    true,
		IsPassed:   isPassed,
		RiskLevel:  riskLevel,
		Violations: violations,
	})
}

// createGreenClientConfig 创建并配置阿里云 Green 客户端配置
func createGreenClientConfig() *openapi.Config {
	return &openapi.Config{
		AccessKeyId:     tea.String("LTAI5t6AsUdBoEXLycEhes9L"),
		AccessKeySecret: tea.String("35eK6gzOsBXFS96nDny8ae7SsdWPLw"),
		RegionId:        tea.String("cn-shanghai"),
		Endpoint:        tea.String("green-cip.cn-shanghai.aliyuncs.com"),
		ConnectTimeout:  tea.Int(3000),
		ReadTimeout:     tea.Int(6000),
	}
}
